﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class NewsClass : Admin_BasePage
{
    protected string classid, classname, readme, picurl, linkurl;
    protected int Pid = 0;//父级ID
    protected int ClsId = 0;
    protected int RepeaterCount = 0;
    DataTable data = new DataTable();
    private void Page_Init(object sender, System.EventArgs e)
    {
        DataColumn dc1 = new DataColumn("Classid");
        DataColumn dc2 = new DataColumn("className");
        DataColumn dc3 = new DataColumn("parentId");
        DataColumn dc4 = new DataColumn("ParentPath");
        DataColumn dc5 = new DataColumn("RootID");
        DataColumn dc6 = new DataColumn("Child");
        DataColumn dc7 = new DataColumn("PrevID");
        DataColumn dc8 = new DataColumn("NextID");
        DataColumn dc9 = new DataColumn("OrderID");
        DataColumn dc10 = new DataColumn("Depth");

        data.Columns.Add(dc1);
        data.Columns.Add(dc2);
        data.Columns.Add(dc3);
        data.Columns.Add(dc4);
        data.Columns.Add(dc5);
        data.Columns.Add(dc6);
        data.Columns.Add(dc7);
        data.Columns.Add(dc8);
        data.Columns.Add(dc9);
        data.Columns.Add(dc10);
    }
    private void bind_tree(string ChildNodes)
    {
        //绑定根节点
        dbclass dbc = new dbclass();
        DataTable dt = dbc.GetSql_DataTable("select * from ArticleClass where parentId=" + ChildNodes + " and Types=1 order by OrderID ");

        foreach (DataRow dr in dt.Rows)
        {
            DataRow dar = data.NewRow();
            dar["Classid"] = dr["Classid"];
            dar["className"] = dr["className"];
            dar["parentId"] = dr["parentId"];
            dar["ParentPath"] = dr["ParentPath"];
            dar["RootID"] = dr["RootID"];
            dar["Child"] = dr["Child"];
            dar["PrevID"] = dr["PrevID"];
            dar["NextID"] = dr["NextID"];
            dar["OrderID"] = dr["OrderID"];
            dar["Depth"] = dr["Depth"];
            data.Rows.Add(dar);

            bind_tree(dr["Classid"].ToString());
        }
        dbc.close();
        dbc.Dispose();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        IsExit();
        if (Request["ParentID"] != null)
        {
            Pid = CommonClass.isNumber_int(Request["ParentID"].ToString());
        }


        if (Request["Classid"] != null)
        {
            ClsId = CommonClass.isNumber_int(Request["Classid"].ToString());
        }



        string strTmp = "abcdefg某某某";
        int i = System.Text.Encoding.Default.GetBytes(strTmp).Length;
        string Action = "";
        CommonClass.Request("Action", out  Action);
        if (Action == "Add")
        {
            this.Pl_Add.Visible = true;
            if (CommonClass.isNumber_int(this.Drop_ParentID.SelectedValue) > 0)
            {
                Pid = CommonClass.isNumber_int(this.Drop_ParentID.SelectedValue);
            }
            if (!Page.IsPostBack)
            {
                bind_tree("0");
                ArticleClass_Bind_DropDownList(Drop_ParentID, Pid, data);
            }

        }
        else if (Action == "Modify")
        {
            this.Pl_Modify.Visible = true;
            if (ClsId <= 0)
            {
                Response.Write("<script>alert('参数传递错误!');history.back();</script>");
                Response.End();
            }
            if (!Page.IsPostBack)
            {
                ArticleClassInfo model = ArticleClass.GetModel(ClsId);
                this.Txt_ModifyName.Text = model._className;
                this.Txt_ModifyReadme.Text = model._Readme;
                this.Txt_ModifypicUrl.Text = model._ClassPicUrl;
                this.Txt_ModifyLinkUrl.Text = model._LinkUrl;
                this.Hid.Value = ClsId.ToString();
                ArticleClass.ArticleClass_Bind_DropDownList(Drop_ParentID, Pid);
            }
        }
        else if (Action == "Move")
        {
            this.Pl_Move.Visible = true;
            if (ClsId <= 0)
            {
                Response.Write("<script>alert('参数传递错误!');history.back();</script>");
                Response.End();
            }
            ArticleClassInfo model_Move = ArticleClass.GetModel(ClsId);
            this.lb_MoveClassName.Text = model_Move._className;
            if (!Page.IsPostBack)
            {
                bind_tree("0");
                ArticleClass_Bind_ListBox(list_Class, model_Move._parentId, data);
                this.Move_ClsID.Value = ClsId.ToString();
            }
        }
        else if (Action == "Order")
        {
            this.pl_OneOrder.Visible = true;
            if (!Page.IsPostBack)
            {
                bind_Parent0();
            }
        }
        else if (Action == "NOrder")
        {
            this.pl_NOrder.Visible = true;
            if (!IsPostBack)
            {
                bind_tree("0");
                this.Repeater2.DataSource = data;
                this.Repeater2.DataBind();
            }
        }
        else
        {
            if (!Page.IsPostBack)
            {
                this.Pl_Manager.Visible = true;
                bind();
            }
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        classid = Drop_ParentID.SelectedValue;
        classname = ClassName.Text;
        readme = Readme.Text;
        picurl = ClassPicUrl.Text;
        linkurl = LinkUrl.Text;

        //ParentID.Text;
        //ClassName.Text;
        //Readme.Text;
        ArticleClassInfo ArtInfo = new ArticleClassInfo();

        ArtInfo._parentId = CommonClass.isNumber_int(classid);
        ArtInfo._className = classname;
        ArtInfo._Readme = readme;
        ArtInfo._ClassPicUrl = picurl;
        ArtInfo._LinkUrl = linkurl;
        ArticleClass.ArticleClassAdd(ArtInfo);
    }

    /// <summary>
    /// 绑定所有分类
    /// </summary>
    protected void bind()
    {
        /*
        dbclass ConnBind = new dbclass();
        DataSet ds = ConnBind.GetSql_DataSet("Select * from ArticleClass order by RootID,OrderID");
        this.Rp_ClassList.DataSource = ds;
        this.Rp_ClassList.DataBind();
        ConnBind.close();
         * */
        bind_tree("0");
        this.Rp_ClassList.DataSource = data;
        this.Rp_ClassList.DataBind();
    }

    protected void bind_Parent0()
    {
        dbclass Conn = new dbclass();
        DataSet ds = Conn.GetSql_DataSet("select * From ArticleClass where ParentID=0 and Types=1 order by OrderID");
        RepeaterCount = ds.Tables[0].Rows.Count;

        this.Repeater1.DataSource = ds;
        this.Repeater1.DataBind();
        Conn.close();
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        dbclass Conn = new dbclass();
        string ClsName = Txt_ModifyName.Text;
        string Readme = Txt_ModifyReadme.Text;
        string pic = Txt_ModifypicUrl.Text;
        string linkUrl = Txt_ModifyLinkUrl.Text;
        int id = CommonClass.isNumber_int(Hid.Value.ToString());
        if (id <= 0)
        {
            Response.Write("<script>alert('参数传递错误!');history.back();</script>");
            Response.End();
        }

        ArticleClassInfo model = ArticleClass.GetModel(id);
        if (model._Child > 0 && linkUrl != "")
        {
            Response.Write("<script>alert('此栏目下包含子分类，不能设置为外部链接!');history.back();</script>");
            Response.End();
        }

        string sql = "Update ArticleClass Set className='" + ClsName + "',Readme='" + Readme + "',ClassPicUrl='" + pic + "',LinkUrl='" + linkUrl + "' Where classid=" + id;
        dbclass ConnUpdate = new dbclass();
        ConnUpdate.Execute_Noget(sql);
        Response.Redirect("Newsclass.aspx");
        Response.End();
    }
    protected void Button3_Click(object sender, EventArgs e)
    {
        string Move_ParentID = list_Class.SelectedValue;
        int Move_OldID = CommonClass.isNumber_int(Move_ClsID.Value);
        if (Move_OldID <= 0)
        {
            Response.Write("<script>alert('参数不足');history.back();</script>");
            Response.End();
        }
        dbclass Conn = new dbclass();
        dbclass.ProceducreParameter[] Parameter = new dbclass.ProceducreParameter[3];
        Parameter[0].dbType = SqlDbType.Int;
        Parameter[0].ObjValue = Move_ParentID;
        Parameter[0].strName = "@ParentId";

        Parameter[1].dbType = SqlDbType.Int;
        Parameter[1].ObjValue = Move_OldID;
        Parameter[1].strName = "@ClassID";

        Parameter[2].dbType = SqlDbType.NVarChar;
        Parameter[2].strName = "@ErrInfo";
        Parameter[2].Size = 500;


        Parameter[2].PdDirection = ParameterDirection.Output;
        object Error;
        Conn.GetProcedu_Output("Article_MoveClass", Parameter, "@ErrInfo", out Error);
        if (Error.ToString() != "")
        {
            Response.Write("<script>alert('" + Error + "');history.back();</script>");
            Response.End();
        }
        else
        {
            Response.Redirect("Newsclass.aspx");
            Response.End();
        }

    }

    protected void Rp_ClassList_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        LinkButton delbtn = e.Item.FindControl("linkbtnDel") as LinkButton;
        DataRowView drv = (DataRowView)e.Item.DataItem;
        if (e.Item.ItemIndex != -1)
        {
            if (Convert.ToInt32(drv["child"]) != 0)
            {
                delbtn.Text = "禁止";
                delbtn.OnClientClick = "";
                delbtn.Enabled = false;
            }
        }

        if (e.Item.ItemType == ListItemType.Footer)
        {
            if (Rp_ClassList.Items.Count == 0)//显示的数据项为0 既是没有数据
            {
                ((Panel)e.Item.FindControl("pl_no")).Visible = true;
            }
        }


    }
    protected void Rp_ClassList_ItemCommand(object source, RepeaterCommandEventArgs e)
    {
        if (e.CommandName == "clearClass")
        {

            object ErrInfo;
            dbclass Conn = new dbclass();
            dbclass.ProceducreParameter[] Parameter = new dbclass.ProceducreParameter[2];

            Parameter[0].dbType = SqlDbType.Int;
            Parameter[0].ObjValue = e.CommandArgument;
            Parameter[0].strName = "@strClassID";

            Parameter[1].dbType = SqlDbType.NVarChar;
            Parameter[1].Size = 500;
            Parameter[1].strName = "@ErrInfo";
            Parameter[1].PdDirection = ParameterDirection.Output;
            Conn.GetProcedu_Output("Clear_class", Parameter, "@ErrInfo", out ErrInfo);


            Response.Write("<script>alert('清空文章内容" + ErrInfo.ToString() + "');</script>");
            if (ErrInfo.ToString() == "成功")
            {
                Response.Write("<script>location.href='Newsclass.aspx';</script>");

            }
            else
            {
                Response.Write("<script>history.back();</script>");
            }

            Response.End();
        }

        if (e.CommandName == "delClass")
        {

            object ErrInfo;
            dbclass Conn = new dbclass();
            dbclass.ProceducreParameter[] Parameter = new dbclass.ProceducreParameter[2];

            Parameter[0].dbType = SqlDbType.Int;
            Parameter[0].ObjValue = e.CommandArgument;
            Parameter[0].strName = "@ClassID";

            Parameter[1].dbType = SqlDbType.NVarChar;
            Parameter[1].Size = 500;
            Parameter[1].strName = "@ErrInfo";
            Parameter[1].PdDirection = ParameterDirection.Output;
            Conn.GetProcedu_Output("DeleteClass", Parameter, "@ErrInfo", out ErrInfo);


            Response.Write("<script>alert('删除文章分类" + ErrInfo.ToString() + "');</script>");
            if (ErrInfo.ToString() == "成功")
            {
                Response.Write("<script>location.href='Newsclass.aspx';</script>");

            }
            else
            {
                Response.Write("<script>history.back();</script>");
            }

            Response.End();
        }

    }



    protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        DropDownList DropUp = e.Item.FindControl("Drop_up") as DropDownList;
        DropDownList DropDown = e.Item.FindControl("Drop_Down") as DropDownList;
        if (e.Item.ItemIndex != -1)
        {
            DropUp.Visible = false;
            DropDown.Visible = false;

            int j = e.Item.ItemIndex + 1;

            if (j > 1)
            {
                for (int i = 1; i <= j - 1; i++)
                {
                    DropUp.Visible = true;
                    ListItem Item = new ListItem();
                    Item.Value = i.ToString();
                    Item.Text = i.ToString();
                    DropUp.Items.Add(Item);
                }
            }
            if (RepeaterCount > j)
            {
                for (int c = 1; c <= RepeaterCount - j; c++)
                {
                    DropDown.Visible = true;
                    ListItem Item = new ListItem();
                    Item.Value = c.ToString();
                    Item.Text = c.ToString();
                    DropDown.Items.Add(Item);
                }
            }
        }


        if (e.Item.ItemType == ListItemType.Footer)
        {
            if (Repeater1.Items.Count == 0)//显示的数据项为0 既是没有数据
            {
                ((Panel)e.Item.FindControl("pl_NoOrder")).Visible = true;
            }
        }
    }

    protected void DropUp_SelectedIndexChanged(object sender, EventArgs e)
    {
        System.Web.UI.WebControls.RepeaterItem item = (RepeaterItem)((Control)sender).Parent;

        HiddenField hid = Repeater1.Items[item.ItemIndex].FindControl("ClassID") as HiddenField;

        HiddenField hid1 = Repeater1.Items[item.ItemIndex].FindControl("cRootID") as HiddenField;
        string MoveClssID = hid.Value;
        string MovecRootID = hid1.Value;
        string UpID = ((DropDownList)sender).SelectedValue;

        // Response.Write(UpID);
        //  Response.End();



        bool FoundErr = false;
        string ErrMsg = "";

        if (MoveClssID == "")
        {
            FoundErr = true;
            ErrMsg = ErrMsg + "当前分类ID出错！</li>\\n\\n";
        }
        if (MovecRootID == "")
        {
            FoundErr = true;
            ErrMsg = ErrMsg + "原栏目级数不能为空！\\n\\n";
        }

        if (CommonClass.isNumber_int(UpID) == 0)
        {
            FoundErr = true;
            ErrMsg = ErrMsg + "请选择要提升的数字！\\n\\n";
        }
        if (FoundErr == true)
        {
            Response.Write("<script>alert('" + ErrMsg + "');location.href='Newsclass.aspx?Action=Order';</script>");
            Response.End();
        }

        dbclass Conn = new dbclass();
        dbclass.ProceducreParameter[] Parameter = new dbclass.ProceducreParameter[3];

        Parameter[0].dbType = SqlDbType.Int;
        Parameter[0].ObjValue = MoveClssID;
        Parameter[0].strName = "@ClassID";

        Parameter[1].dbType = SqlDbType.Int;
        Parameter[1].ObjValue = MovecRootID;
        Parameter[1].strName = "@cRootID";

        Parameter[2].dbType = SqlDbType.Int;
        Parameter[2].ObjValue = UpID;
        Parameter[2].strName = "@MoveNum";
        Conn.GetProcedureNoRun("UpOrder_ArticleClass", Parameter);
        Response.Redirect("Newsclass.aspx?Action=Order");
        Response.End();

    }
    #region 显示数据处理
    protected void Repeater2_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
        {
            Label lbl_classname_Img = (Label)e.Item.FindControl("lbl_ClassName_Img");
            HiddenField hd_ClassID = (HiddenField)e.Item.FindControl("_ClassID");
            HiddenField hd_className = (HiddenField)e.Item.FindControl("_className");
            HiddenField hd_parentId = (HiddenField)e.Item.FindControl("_parentId");
            HiddenField hd_ParentPath = (HiddenField)e.Item.FindControl("_ParentPath");
            HiddenField hd_Depth = (HiddenField)e.Item.FindControl("_Depth");
            HiddenField hd_RootID = (HiddenField)e.Item.FindControl("_RootID");
            HiddenField hd_Child = (HiddenField)e.Item.FindControl("_Child");
            HiddenField hd_PrevID = (HiddenField)e.Item.FindControl("_PrevID");
            HiddenField hd_NextID = (HiddenField)e.Item.FindControl("_NextID");
            string ss = hd_ClassID.Value;

            string LitStyle = "<span style=width:{0}px;text-align:right;display:inline-block;>{1}{2}</span>";

            //  -
            string LitImg1_1 = "<img src='" + configInfo.InstallDir + "images/tree_folder3.gif' align=absmiddle />";
            //   + 
            string LitImg1_2 = "<img src='" + configInfo.InstallDir + "images/tree_folder4.gif' align=absmiddle />";
            //   ┗
            string LitImg2_1 = "<img src='" + configInfo.InstallDir + "images/tree_line2.gif' align=absmiddle />";
            //   ┣
            string LitImg2_2 = "<img src='" + configInfo.InstallDir + "images/tree_line1.gif' align=absmiddle />";
            int ClassTj = Convert.ToInt32(hd_Depth.Value) + 1;

            string Img1 = "";
            string Img2 = "";
            if (hd_Child.Value == "0")
            {
                Img1 = LitImg1_1;
            }
            else
            {
                Img1 = LitImg1_2;
            }

            //HiddenField prev_hd_parentID = (HiddenField)Repeater1.Items[e.Item.ItemIndex - 1 ].FindControl("_parentId")
            if (hd_parentId.Value == "0")
            {
                Img2 = "";
            }
            else if (hd_NextID.Value != "0")
            {
                Img2 = LitImg2_1; //LitImg2_2
            }
            else
            {
                Img2 = LitImg2_1;
            }
            lbl_classname_Img.Text = string.Format(LitStyle, ClassTj * 20, Img2, Img1);

        }
    }
    #endregion
    private bool Update_ArticleClass(string id, int orderID)
    {
        string strsql = string.Format("update ArticleClass set OrderID={0} where Classid={1}", orderID, id);
        dbclass dbc = new dbclass();
        dbc.ExecuteReRow_SQL(strsql);

        return true;
    }
    protected void btn_NSave_Click(object sender, EventArgs e)
    {
        int UpSum = 0;
        bool ReVal = true;
        foreach (RepeaterItem RptItem in this.Repeater2.Items)
        {
            HiddenField hd_ClassID = (HiddenField)RptItem.FindControl("_ClassID");
            TextBox txt_order_ID = (TextBox)RptItem.FindControl("txt_order_ID");

            try
            {
                ReVal = Update_ArticleClass(hd_ClassID.Value, Convert.ToInt32(txt_order_ID.Text));
            }
            catch
            {
                ReVal = false;
            }

            if (ReVal == false)
            {
                ++UpSum;
            }
        }

        if (UpSum == 0)
        {
            Page.ClientScript.RegisterStartupScript(Page.GetType(), "ajaxjs", "alert('所有设定的栏目顺序都已保存成功！')", true);
        }
        else
        {
            Page.ClientScript.RegisterStartupScript(Page.GetType(), "ajaxjs", string.Format("alert('栏目顺序部份保存成功,共有{0}条记录保存失败!')", UpSum), true);
        }
        //bind_tree("0");
        //this.Repeater2.DataSource = data;
        //this.Repeater2.DataBind();
        Response.Redirect("Newsclass.aspx?Action=NOrder");
    }
    //移动
    private void ArticleClass_Bind_ListBox(ListBox Drop, int ParentID, DataTable dt)
    {
        Drop.Items.Add(new ListItem("无(作为一级栏目)", "0"));
        //dbclass ConnBind = new dbclass();
        //DataTable dt = ConnBind.GetSql_DataSet("Select * from ArticleClass order by RootID,OrderID").Tables[0];
        bool[] arrShowLine = new bool[dt.Rows.Count];

        foreach (DataRow dr in dt.Rows)
        {
            ArticleClassInfo model = ArticleClass.GetModel(Convert.ToInt32(dr["Classid"].ToString()));

            /*
            string LitStyle = "{0}{1}{2}";
            //  -
            string LitImg1_1 = "-";
            //   + 
            string LitImg1_2 = "+";
            //   ┗
            string LitImg2_1 = "┗";
            //   ┣
            string LitImg2_2 = "<img src='" + CommonClass.ReWebConfig("webdir").ToString() + "Master/images/tree_line1.gif' align=absmiddle />";
            int ClassTj = Convert.ToInt32(model._Depth) + 1 ;
            string  spaceNum = "| " ;

            for (int j = 0; j < ClassTj * 20 ; j++)
            {
                spaceNum = spaceNum + "  "; 
            }

            string Img1 = "";
            string Img2 = "";
            if (model._Child == 0)
            {
                Img1 = LitImg1_1;
            }
            else
            {
                Img1 = LitImg1_2;
            }

            //HiddenField prev_hd_parentID = (HiddenField)Repeater1.Items[e.Item.ItemIndex - 1 ].FindControl("_parentId")
            if (model._parentId == 0)
            {
                Img2 = " ";
            }
            else
            {
                Img2 = LitImg2_1;
            }
            string Result = string.Format(LitStyle, spaceNum , Img2, Img1);
            Result += model._className;
            ListItem Item = new ListItem();
            Item.Text = Result;
            Item.Value = model._Classid.ToString();
            Drop.Items.Add(Item);
             * */
            if (model._NextID > 0)
            {
                arrShowLine[model._Depth] = true;
            }
            else
            {
                arrShowLine[model._Depth] = false;
            }
            string Result = " ";
            if (model._Depth > 0)
            {
                for (int i = 1; i <= model._Depth; i++)
                {
                    if (i == model._Depth)
                    {
                        if (model._NextID > 0)
                        {
                            Result += "├";
                        }
                        else
                        {
                            Result += "└";
                        }
                    }
                    else
                    {
                        if (arrShowLine[i] == true)
                        {
                            Result += "│";
                        }
                        else
                        {
                            Result += "　";
                        }
                    }
                }
            }
            Result += model._className;
            ListItem Item = new ListItem();
            Item.Text = Result;
            Item.Value = model._Classid.ToString();
            Drop.Items.Add(Item);
        }
        Drop.Items.FindByValue(ParentID.ToString()).Selected = true;
    }
    /// <summary>
    /// 绑定DropDownList控件
    /// </summary>
    /// <param name="Drop">DropDownList控件对象</param>
    /// <param name="ParentID">父级ID</param>
    public static void ArticleClass_Bind_DropDownList(DropDownList Drop, int ParentID, DataTable dt)
    {
        Drop.Items.Add(new ListItem("无(作为一级栏目)", "0"));
        //dbclass ConnBind = new dbclass();
        //DataTable dt = ConnBind.GetSql_DataSet("Select * from ArticleClass order by RootID,OrderID").Tables[0];
        bool[] arrShowLine = new bool[dt.Rows.Count];

        foreach (DataRow dr in dt.Rows)
        {
            ArticleClassInfo model = ArticleClass.GetModel(Convert.ToInt32(dr["Classid"].ToString()));

            if (model._NextID > 0)
            {
                arrShowLine[model._Depth] = true;
            }
            else
            {
                arrShowLine[model._Depth] = false;
            }
            string Result = " ";
            if (model._Depth > 0)
            {
                for (int i = 1; i <= model._Depth; i++)
                {
                    if (i == model._Depth)
                    {
                        if (model._NextID > 0)
                        {

                            Result += "├";
                        }
                        else
                        {
                            Result += "└";
                        }
                    }
                    else
                    {
                        if (arrShowLine[i] == true)
                        {
                            Result += "│";
                        }
                        else
                        {
                            Result += "　";
                        }
                    }
                }
            }
            Result += model._className;
            ListItem Item = new ListItem();
            Item.Text = Result;
            Item.Value = model._Classid.ToString();
            Drop.Items.Add(Item);
        }
        Drop.Items.FindByValue(ParentID.ToString()).Selected = true;

    }
}
